import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/// 多个TextField密码校验
class MultiTextFieldExample extends StatefulWidget {
  const MultiTextFieldExample({super.key});

  @override
  State<MultiTextFieldExample> createState() => _MultiTextFieldExampleState();
}

class _MultiTextFieldExampleState extends State<MultiTextFieldExample> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: const Column(
        children: <Widget>[
          MultiTextFieldWidget(),
        ],
      ),
    );
  }
}

class MultiTextFieldWidget extends StatefulWidget {
  final int count;

  const MultiTextFieldWidget({
    super.key,
    this.count = 8,
  });
  @override
  MultiTextFieldWidgetState createState() => MultiTextFieldWidgetState();
}

class MultiTextFieldWidgetState extends State<MultiTextFieldWidget> {
  final map = <int, _TextFieldValue>{};

  @override
  void initState() {
    super.initState();
    for (var i = 0; i < widget.count; i++) {
      map.putIfAbsent(i, () => _TextFieldValue());
    }
  }

  String getText() {
    final sb = StringBuffer();
    for (var i = 0; i < widget.count; i++) {
      final value = map[i];
      var text = value?.controller.text ?? '';
      if (text.isNotEmpty) {
        text = text.substring(0, 1);
      } else {
        text = ' ';
      }
      sb.write(text);
    }
    return sb.toString();
  }

  void clear() {
    for (var i = 0; i < widget.count; i++) {
      final value = map[i];
      value?.controller.clear();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        for (var i = 0; i < widget.count; i++) _buildTextFiled(i),
      ],
    );
  }

  Widget _buildTextFiled(int i) {
    final value = map[i];
    return Expanded(
      child: CupertinoTextField(
        focusNode: value?.node,
        controller: value?.controller,
        onChanged: (v) {
          if (v.length > 1) {
            value?.controller.text = v.substring(0, 1);
            return;
          }
          if (i != widget.count - 1) {
            if (v.isEmpty) {
              // 为空则返回上一个
              if (i != 0) {
                map[i - 1]?.node.requestFocus();
              }
            } else {
              // 跳到下一个
              map[i + 1]?.node.requestFocus();
            }
          } else {
            // 关闭并校验
            if (v.isEmpty) {
              map[i - 1]?.node.requestFocus();
              return;
            }
            value?.node.unfocus();
            print("最后一个了, 文字为: ${getText()}");
          }
        },
      ),
    );
  }
}

class _TextFieldValue {
  FocusNode node = FocusNode();
  TextEditingController controller = TextEditingController();
}
